package cn.lichenes.controller;

import cn.lichenes.entity.Collect;
import cn.lichenes.entity.User;
import cn.lichenes.log.SystemLog;
import cn.lichenes.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class CollectController {

    @Autowired
    private CollectService collectService;

    @SystemLog(value = "用户添加收藏夹",status = "user")
    @PostMapping("/collect")
    @ResponseBody
    public boolean collect(Integer pid, HttpSession session){
        System.out.println(pid);
        User user = (User) session.getAttribute("user");
        if (user != null){
            return collectService.add(user, pid);
        }
        return false;
    }

    @GetMapping("/wishlist")
    public  String wishlist(HttpSession session, @RequestParam(value = "page",defaultValue = "1") Integer page, Model model){
        User user = (User) session.getAttribute("user");
        if (user != null){
            Page<Collect> collectPage = collectService.findAll(user, page);
            Map<String,Object> map = new HashMap<>();
            List<Collect> collects = collectPage.getContent();
            map.put("collects", collects);
            map.put("currentPage",page);
            map.put("totalPages",collectPage.getTotalPages());
            model.addAllAttributes(map);
            return "wishlist";

        }
        return "redirect:/login";
    }

    @SystemLog(value = "用户删除收藏商品",status = "user")
    @DeleteMapping("/wishlist/{id}")
    public String deleteWishlist(@PathVariable("id") Integer id){
        System.out.println(id);
        boolean flag = collectService.delete(id);
        return "redirect:/wishlist";
    }
}
